# -*- coding: utf-8 -*-
"""
基础场景模板 - 所有Manim场景的基类
"""

from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional
from pathlib import Path

from .visual_standards import VisualStandards, Theme
from ..time_sync import TimeScaler


class BaseSceneTemplate(ABC):
    """Manim场景基类模板"""

    def __init__(
        self,
        title: str = "",
        narration: str = "",
        audio_duration: float = 0.0,
        subtitle_file: Optional[Path] = None,
        theme: Theme = Theme.DARK,
    ):
        """
        初始化场景模板

        Args:
            title: 场景标题
            narration: 场景叙述
            audio_duration: 音频时长
            subtitle_file: 字幕文件路径
            theme: 主题
        """
        self.title = title
        self.narration = narration
        self.audio_duration = audio_duration
        self.subtitle_file = subtitle_file
        self.theme = theme
        self.visual_standards = VisualStandards(theme)
        self.scaler: Optional[TimeScaler] = None

    @abstractmethod
    def create_content(self, scene) -> Any:
        """
        创建场景内容

        Args:
            scene: Manim场景对象

        Returns:
            创建的内容对象
        """
        pass

    @abstractmethod
    def animate_content(self, scene, content) -> None:
        """
        动画内容

        Args:
            scene: Manim场景对象
            content: 内容对象

        Returns:
            None
        """
        pass

    def setup_scene(self, scene) -> None:
        """
        设置场景

        Args:
            scene: Manim场景对象
        """
        # 初始化TimeScaler
        if self.audio_duration > 0 and self.subtitle_file:
            self.scaler = TimeScaler(
                scene=scene,
                audio_duration=self.audio_duration,
                subtitle_file=self.subtitle_file,
            )

    def get_style(self, element_type: str) -> Dict[str, Any]:
        """
        获取元素样式

        Args:
            element_type: 元素类型

        Returns:
            样式字典
        """
        return self.visual_standards.create_style_dict(element_type)

    def get_color(self, color_name: str) -> str:
        """
        获取颜色

        Args:
            color_name: 颜色名称

        Returns:
            颜色值
        """
        return self.visual_standards.get_color(color_name)

    def get_font_size(self, size_type: str) -> int:
        """
        获取字体大小

        Args:
            size_type: 大小类型

        Returns:
            字体大小
        """
        return self.visual_standards.get_font_size(size_type)

    def get_position(self, position_type: str) -> float:
        """
        获取位置

        Args:
            position_type: 位置类型

        Returns:
            位置坐标
        """
        return self.visual_standards.get_position(position_type)

    def get_animation_config(self, animation_type: str) -> float:
        """
        获取动画配置

        Args:
            animation_type: 动画类型

        Returns:
            动画时长
        """
        return self.visual_standards.get_animation_config(animation_type)

    def sync_to_time(self, scene, time: float) -> None:
        """
        同步到指定时间

        Args:
            scene: Manim场景对象
            time: 目标时间
        """
        if self.scaler and self.scaler.current_time < time:
            wait_time = time - self.scaler.current_time
            scene.wait(wait_time)
            self.scaler.current_time = time

    def wait_for_narration(self, scene, fraction: float = 1.0) -> float:
        """
        等待叙述时长

        Args:
            scene: Manim场景对象
            fraction: 时长比例

        Returns:
            等待时间
        """
        if self.scaler and self.narration:
            # 假设叙述是第一个字幕
            duration = (self.audio_duration / 10.0) * fraction  # 简化计算
            scene.wait(duration)
            return duration
        return 0.0

    def get_estimated_duration(self) -> float:
        """
        获取估计场景时长

        Returns:
            时长（秒）
        """
        return self.audio_duration if self.audio_duration > 0 else 10.0

    def validate(self) -> tuple[bool, list]:
        """
        验证场景配置

        Returns:
            (是否有效, 错误列表)
        """
        errors = []

        # 检查主题配置
        is_valid, theme_errors = self.visual_standards.validate_theme()
        if not is_valid:
            errors.extend(theme_errors)

        # 检查必要字段
        if not self.title and not self.narration:
            errors.append("At least one of title or narration must be provided")

        # 检查音频时长
        if self.audio_duration < 0:
            errors.append("Audio duration must be non-negative")

        # 检查字幕文件
        if self.subtitle_file and not self.subtitle_file.exists():
            errors.append(f"Subtitle file not found: {self.subtitle_file}")

        return len(errors) == 0, errors

    def __str__(self) -> str:
        """返回场景的字符串表示"""
        return f"{self.__class__.__name__}(title='{self.title[:20]}...', duration={self.audio_duration:.1f}s)"

    def __repr__(self) -> str:
        """返回场景的详细字符串表示"""
        return (
            f"{self.__class__.__name__}("
            f"title='{self.title}', "
            f"narration='{self.narration[:30]}...', "
            f"audio_duration={self.audio_duration}, "
            f"theme={self.theme.value}"
            f")"
        )
